package com.usian.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.usian.CartFeign;
import com.usian.ItemFeign;
import com.usian.pojo.TbItem;
import com.usian.utils.CookieUtils;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.management.ObjectName;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTMLDocument;
import java.util.*;

@RestController
@RequestMapping("/frontend/cart")
public class CartController {

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private ItemFeign itemFeign;

    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Value("${CART_REDIS_KEY}")
    private String CART_REDIS_KEY;

    @Value("${CART_COOKIE_EXPIRE}")
    private Integer CART_COOKIE_EXPIRE;


    /**
     * 添加购物车（未登录和已登录）
     * @param userId
     * @param itemId
     * @return
     */
    @RequestMapping("addItem")
    public Result addItem(@RequestParam String userId, @RequestParam Long itemId,
      HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(defaultValue = "1") int num){

        if(StringUtils.isBlank(userId)){
            //未登录

            //1：从cookie中获取购物车信息转换成map集合
            Map<String ,Object> map = getCartFromCookie(request);

            //2:添加商品到购物车
            addItemToCart(map,itemId,num);

            //3:写到cookie
            addClientCookie(request,response,map);

            return Result.ok("OK");
        }else{
            //已登录
            Map<String, Object> cart = this.getCartFromRedis(userId);

            //2:添加商品到购物车
            addItemToCart(cart,itemId,num);

            //3:写到redis
            addCartToRedis(userId,cart);

            return Result.ok("OK");
        }

    }

    /**
     * 未登录状态下去cookie获取购物车信息
     *
     * @param request
     * @return
     */
    private Map<String, Object> getCartFromCookie(HttpServletRequest request){

        String cookieValue = CookieUtils.getCookieValue(request, CART_COOKIE_KEY, true);
        if(StringUtils.isNotBlank(cookieValue)){
            Map<String, Object> map = JsonUtils.jsonToMap(cookieValue, TbItem.class);
            return map;
        }

        return new HashMap<String, Object>();
    }


    /**
     * 未登录状态下去cookie获取购物车信息
     *
     * @param userId
     * @return
     */
    private Map<String, Object> getCartFromRedis(String userId){

        Map<String, Object>  redisMap = cartFeign.getCartByUserId(userId);
        return redisMap;
    }

    /**
     * 未登录状态下加入购物车逻辑判断
     *
     * @param cart
     * @param itemId
     * @param num
     */
    private  void  addItemToCart(Map<String,Object> cart,Long itemId,int num ){
        //1:从购物车把商品取出来
        TbItem tbItem = (TbItem)cart.get(itemId);
        //2:拿到的  数量累加   没拿到 mysql 只接放商品对象
        if(tbItem!=null){
            //有
            tbItem.setNum(tbItem.getNum()+num);
        }else{
            //没有
            tbItem = itemFeign.selectItemInfo(itemId);  //mysql feign
            tbItem.setNum(num);
        }
        cart.put(itemId.toString(),tbItem);
    }

    /**
     * 未登录状态下 购物车存入cookie
     */
    private void addClientCookie(HttpServletRequest request, HttpServletResponse response,
                                 Map<String ,Object> map){
        //把map 转json字符串
        String cartJsonString = JsonUtils.objectToJson(map);

        //存cookie
        CookieUtils.setCookie(request,response,CART_COOKIE_KEY,cartJsonString,CART_COOKIE_EXPIRE,true);
    }

    private boolean addCartToRedis(String userId,Map<String,Object> cart){
        return cartFeign.addCartToRedis(userId,cart);
    }

    /**
     * 未登录状态下查询购物车
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("showCart")
    public Result  showCart(@RequestParam String userId,HttpServletRequest request){

        if(StringUtils.isBlank(userId)){

            Map<String ,Object> map = getCartFromCookie(request);
            Set<String> keySet = map.keySet();

            List<TbItem> list =new ArrayList<>();

            for(String key :keySet){
                TbItem tbItem = (TbItem)map.get(key);
                list.add(tbItem);
            }
            return Result.ok(list);

        }else{

            Map<String ,Object> map = this.getCartFromRedis(userId);
            Set<String> keySet = map.keySet();

            List list =new ArrayList<>();

//            map.forEach((key,value)->{
//                System.out.println(key +"===="+value);
//            });
//
//            for(Map.Entry<String,Object> m :map.entrySet()){
//                String key = m.getKey();
//                Object value = m.getValue();
//                System.out.println(key +"===="+value);
//            }

            for(String key :keySet){

                ObjectMapper objectMapper =new ObjectMapper();
                TbItem tbItem =objectMapper.convertValue(map.get(key),TbItem.class);

                list.add(tbItem);
            }
            return Result.ok(list);
        }
    }


    /**
     * 修改购物车（未登录和已登录）
     * @param userId
     * @param itemId
     * @return
     */
    @RequestMapping("updateItemNum")
    public Result updateItemNum(@RequestParam String userId, @RequestParam Long itemId,
                          HttpServletRequest request, HttpServletResponse response,
                          @RequestParam int num){

        if(StringUtils.isBlank(userId)){
            //未登录

            //1：从cookie中获取购物车信息转换成map集合
            Map<String ,Object> map = getCartFromCookie(request);

            //2: 修改购物车  num 直接覆盖   添加购物车时 num做加法运算
            TbItem tbItem = (TbItem)map.get(itemId.toString());
            tbItem.setNum(num);
            map.put(itemId.toString(),tbItem);

            //3:写到cookie
            addClientCookie(request,response,map);
            return Result.ok("OK");
        }else{

            Map<String, Object> redisMap = this.getCartFromRedis(userId);

            //修改购物车数量
            ObjectMapper objectMapper =new ObjectMapper();
            TbItem tbItem = objectMapper.convertValue(redisMap.get(itemId.toString()), TbItem.class);
            tbItem.setNum(num);
            redisMap.put(itemId.toString(),tbItem);

            //写入redis
            addCartToRedis(userId,redisMap);

            return Result.ok("OK");
        }
    }

    /**
     * 删除购物车
     * @param userId
     * @param itemId
     * @return
     */
    @RequestMapping("deleteItemFromCart")
    public Result deleteItemFromCart(@RequestParam String userId, @RequestParam Long itemId,
                                     HttpServletRequest request,HttpServletResponse response
                                ){

        if(StringUtils.isBlank(userId)){
            //未登录

            //1：从cookie中获取购物车信息转换成map集合
            Map<String ,Object> map = getCartFromCookie(request);

            //2: 修改购物车  num 直接覆盖   添加购物车时 num做加法运算
            //TbItem tbItem = (TbItem)map.get(itemId);
            map.remove(itemId.toString());

            //3:写到cookie
            addClientCookie(request,response,map);
            return Result.ok("OK");
        }else{
            Map<String, Object> redisMap = this.getCartFromRedis(userId);

            redisMap.remove(itemId.toString());

            //写入redis
            addCartToRedis(userId,redisMap);

            return Result.ok("OK");
        }
    }

}
